package core.controller.cmds;

import utilities.CommonUtil;
import core.controller.CommandController;
import core.dal.OperatorFunctionality;
import exceptions.UserNotFoundException;
import exceptions.WrongPasswordException;

public class LoginCMD implements ICmd {

	OperatorFunctionality functionality;
	final String level = "Login";
	ICmd nextCMD;

	CommandController cc;

	public LoginCMD(CommandController commandController,
			OperatorFunctionality oF) {
		this.cc = commandController;
		functionality = oF;
	}

	@Override
	public void setNextCmd(ICmd nextCmd) {
		nextCMD = nextCmd;

	}

	@Override
	public void execute(String cmd) {
		if (cmd.equals("login")) {
			String idString;
			int id;
			String pass;

			cc.getTUI().showOutput("Enter ID: ");
			idString = cc.getTUI().getInput();

			//prompts and error to the user if id contains anything other than numbers
			if (CommonUtil.isNumber(idString)) {
				id = Integer.parseInt(idString);
				
				cc.getTUI().showOutput("Enter Pass: ");
				pass = cc.getTUI().getInput();
				
				try {
					//Sets admin user if admin
					if (functionality.login(id, pass).isAdmin()) {
						cc.setCurrentLevel("Admin");
						cc.setCurrentUser(functionality.login(id, pass));
						cc.getTUI().showOutput(
								"LOGGED IN AS: "
										+ cc.getCurrentUser().getOprNavn()
										+ " - Admin");
					} else {
					//Sets Operator user if operator
						cc.setCurrentLevel("Operator");
						cc.setCurrentUser(functionality.login(id, pass));
						cc.getTUI().showOutput(
								"LOGGED IN AS: "
										+ cc.getCurrentUser().getOprNavn()
										+ " - Operator");
					}

				} catch (UserNotFoundException e) {
					cc.getTUI().showOutput(e.getMessage());
				} catch (WrongPasswordException e2) {
					cc.getTUI().showOutput(e2.getMessage());
				}
			}
			else{
				cc.getTUI().showOutput("ID MAY ONLY CONTAIN NUMBERS");
			}

		} else {
			cc.getTUI().showOutput("ENTER VALID CMD");
		}

		if (nextCMD != null) {
			nextCMD.execute(cmd);
		}

	}

	@Override
	public String getInfo() {
		return "login - Enter a name and password to login";

	}

	@Override
	public String getLevel() {
		return this.level;

	}
}
